const webpack = require('webpack')
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const WebpackBar = require('webpackbar')

const devMode = process.env.NODE_ENV === 'development'
const resolve = {
  extensions: ['.js', '.scss'],
  alias: {
    '@': path.resolve('src'),
    root: __dirname,
  },
}

/**
 * 配置 autoprefixer 各浏览器前缀
 * postcss-flexbugs-fixes 检查flex错误
 *  */
const postcssConfig = {
  loader: 'postcss-loader',
  options: {
    plugins: () => [require('autoprefixer')],
  },
}

module.exports = {
  name: 'client',
  target: 'web',

  resolve: resolve,

  output: {
    path: path.resolve(__dirname, '..', devMode ? 'public' : 'dist'),
    filename: devMode ? 'js/[name].bundle.js' : 'js/[name].min.js',
    publicPath: './',
  },

  resolveLoader: {
    moduleExtensions: ['-loader'],
  },

  optimization: {
    // namedModules: true,
    // noEmitOnErrors: true,
    minimize: devMode ? false : true,
    minimizer: [
      new TerserPlugin({
        cache: true,
        parallel: true,
        sourceMap: true,
        terserOptions: {
          compress: {
            // 关键代码
            warnings: true,
            drop_debugger: true,
            drop_console: true,
          },
        },
      }),
    ],
    splitChunks: {
      cacheGroups: {
        // 把所有的CSS打包到一个文件
        // styles: {
        //   name: 'styles',
        //   test: /(\.css|\.scss)$/,
        //   chunks: 'all',
        //   enforce: true,
        // },
        commons: {
          name: 'vendor',
          test: /[\\/]node_modules[\\/]/,
          chunks: 'all',
        },
      },
    },
  },

  module: {
    strictExportPresence: true,
    rules: [
      // js 文件解析
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: ['@babel/preset-env'],
            },
          },
        ],
      },
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              hmr: devMode,
            },
          },
          'css-loader',
          'sass-loader',
          {
            ...postcssConfig,
          },
        ],
      },

      // 小于8K的图片，转 base64
      {
        test: /\.(png|jpe?g|gif|bmp|svg)$/,
        use: [
          {
            loader: 'url',
            options: {
              // 配置图片编译路径
              limit: 40000, // 小于8k将图片转换成base64
              name: '[name].[hash:8].[ext]',
              outputPath: 'images/',
            },
          },
          {
            loader: 'image-webpack', // 图片压缩
            options: {
              bypassOnDebug: true,
            },
          },
        ],
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url',
        options: {
          limit: 8192,
          name: 'fonts/[name].[hash:8].[ext]',
        },
      },
    ],
  },
  externals: {
    jquery: 'window.$',
    layer: 'window.layer',
    qrcode: 'window.qrcode',
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(), //在输出阶段时，遇到编译错误跳过
    // 提取css插件
    new MiniCssExtractPlugin({
      filename: devMode ? 'css/[name].css' : 'css/[name].min.css',
      chunkFilename: '[id].min.css',
      ignoreOrder: true,
    }),
    new WebpackBar(),
  ],
}
